package com.cxs.distributeddemo.slice;

import com.cxs.distributeddemo.ResourceTable;
import com.cxs.distributeddemo.util.KvStoreUtils;
import com.cxs.distributeddemo.util.UIUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.data.distributed.common.KvStoreException;
import ohos.data.distributed.user.SingleKvStore;

public class MainAbilitySlice extends AbilitySlice {
    Button btnWrite, btnDelete, btnRead, btnCloseDB, btnDelDB;
    // 单版本分布式数据库
    SingleKvStore kvStore = null;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        // 获取数据库
        kvStore = KvStoreUtils.getKvStore(MainAbilitySlice.this);

        btnWrite = (Button)findComponentById(ResourceTable.Id_btn_write);
        btnWrite.setClickedListener(c -> {
            // 向分布式数据库写入数据
            kvStore.putString("test", "我爱鸿蒙");
            UIUtils.showTip(MainAbilitySlice.this, "写入成功");
        });

        btnRead = (Button)findComponentById(ResourceTable.Id_btn_read);
        btnRead.setClickedListener(c -> {
            // 从分布式数据库读取指定key的数据
            String testStr = "";
            try {
                testStr = kvStore.getString("test");
            } catch (KvStoreException exception) {
                UIUtils.showTip(MainAbilitySlice.this, "【无数据】");
            }
            UIUtils.showTip(MainAbilitySlice.this, testStr);
        });

        btnDelete = (Button)findComponentById(ResourceTable.Id_btn_del);
        btnDelete.setClickedListener(c -> {
            kvStore.delete("test");
            UIUtils.showTip(MainAbilitySlice.this, "删除成功");
        });

        btnCloseDB = (Button)findComponentById(ResourceTable.Id_btn_closedb);
        btnCloseDB.setClickedListener(c -> {
            KvStoreUtils.closeDB(kvStore);
            UIUtils.showTip(MainAbilitySlice.this, "关闭数据库");

        });

        btnDelDB = (Button)findComponentById(ResourceTable.Id_btn_deldb);
        btnDelDB.setClickedListener(c -> {
            KvStoreUtils.delDB();
            UIUtils.showTip(MainAbilitySlice.this, "删除数据库");

        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
